#ifndef RANDOM_SELECT_HPP
#define RANDOM_SELECT_HPP

#include <random>
#include <mutex>

#include "./LoadBalancePolicyIface.h"

namespace LoadBalance
{
    template <typename T>
    class RandomSelect : public LoadBalancePolicyIface<T>
    {
    public:
        explicit RandomSelect(const std::vector<T> &nodes) : nodes_(nodes)
        {
        }

        T getNext() override
        {
            std::lock_guard<std::mutex> lock(this->mtx_);

            if (this->nodes_.empty()) // 注意错误处理
            {
                return T{};
            }

            std::uniform_int_distribution<size_t> dist(0, this->nodes_.size() - 1); // 随机索引
            size_t randomIdx = dist(this->randomEngine_);
            return this->nodes_[randomIdx];
        }

    private:
        std::vector<T> nodes_;
        std::mt19937 randomEngine_; // 随机数引擎/生成器
        std::mutex mtx_;            // 注意线程安全
    };
} // namespace LoadBalance

#endif // RANDOM_SELECT_HPP